import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login.vue'
import DataScreen from '@/views/DataScreen.vue'
import { checkLoginService } from '@/api/user.js'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/data-screen',
    name: 'DataScreen',
    component: DataScreen
  }
]

const router = createRouter({
    history: createWebHistory(),
    routes: routes
})

// 添加路由守卫
router.beforeEach(async (to, from, next) => {
  if (to.path !== '/login') {
    try {
      // 添加延迟
      await new Promise(resolve => setTimeout(resolve, 1000))
      const result = await checkLoginService()
      if (result.code === 0) {
        ElMessage.error(result.message || '未登录')
        return next('/login')
      }
    } catch (error) {
      ElMessage.error('请先登录')
      return next('/login')
    }
  }
  next()
})

export default router
